import React, { useState, useEffect, useRef } from 'react';
import { useDeepCompareEffect } from 'ahooks';
import {
  formAddressApi,
  formSaveDrafts,
  activityDetailApi,
} from '@/api/createActivity.js';
import './addCreateActivity.less';
import ApplyActive from './applyActive';
import VoteActive from './voteActive';
import {
  Form,
  Input,
  Cascader,
  DatePicker,
  Upload,
  Button,
  Space,
  Collapse,
} from 'antd';
import {
  LoadingOutlined,
  PlusOutlined,
  MinusCircleOutlined,
  CloseCircleOutlined,
  CaretRightOutlined,
  CaretUpOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
export default function (props) {
  const [form] = Form.useForm();
  const { RangePicker } = DatePicker;
  const son = useRef(null);
  const son1 = useRef(null);
  const [options, setOptions] = useState([]);
  //////////
  const [loading, setLoding] = useState(false);
  const [imageUrl, setImageUrl] = useState('');
  const [loading1, setLoding1] = useState(false);
  const [imageUrl1, setImageUrl1] = useState('');
  const [isShow, setIsShow] = useState(true);
  // const [imageData, setImageData] = useState({});
  // const [imageData1, setImageData1] = useState({});
  const moment = require('moment');
  const [allData, setAllData] = useState([]);

  useEffect(() => {
    add();
  }, []);

  // useEffect(() => {
  //   add1();
  // }, [JSON.stringify(options)]);

  useDeepCompareEffect(() => {
    add1();
  }, [options]);

  async function add1() {
    const res1 = await activityDetailApi(props.history.location.state);
    console.log(res1);
    if (res1.data.code == 200) {
      // let z = [
      //   {
      //     value: res1?.data.data.provinceCode,
      //     label: res1?.data.data.provinceName,
      //     isLeaf: false,
      //     parentId: res1?.data.data.provinceCode,
      //   },
      // ];
      // loadData1(z);
      // console.log('zzzzzzzzz', z);

      editFnLoadData([
        {
          label: res1?.data.data.provinceName,
          parentId: res1?.data.data.provinceCode,
        },
        {
          label: res1?.data.data.cityName,
          parentId: res1?.data.data.cityCode,
        },
      ]);

      let m = res1.data.data.scheduleVOS.map((item) => ({
        scheduleName: item.scheduleName,
        scheduleDate: moment(item.scheduleDate),
      }));
      // console.log(res1.data.data);
      setAllData(res1.data.data.activityVOS);
      setImageUrl1(res1.data.data.pictureUrl);
      setImageUrl(res1.data.data.thumbnailPictureUrl);
      form.setFieldsValue({
        activityName: res1.data.data.activityName,
        // activityArea: [res1.data.data.provinceName, res1.data.data.cityName],
        activityArea: [res1.data.data.provinceCode, res1.data.data.cityCode],
        activityTime: [
          moment(res1.data.data.startDate),
          moment(res1.data.data.endDate),
        ],
        activitySite: res1.data.data.activitySite,
        activityOrganizers: res1.data.data.activityOrganizers,
        activityContent: res1.data.data.activityContent,
        scheduleName: m,
        activityImg_3: [
          {
            uid: '-1',
            name: res1.data.data.pictureKey,
            url: res1.data.data.pictureUrl,
          },
        ],
        activityImg_2: [
          {
            uid: '-2',
            name: res1.data.data.thumbnailPictureKey,
            url: res1.data.data.thumbnailPictureUrl,
          },
        ],
      });

      res1.data.data.activityVOS.forEach((item) => {
        oneClick(item.activityType);
      });
    }
  }

  async function add() {
    const res = await getAddressFn(1);
    if (res.data.code === 200) {
      let arr = res.data.data.map((item) => ({
        value: item.addressCode,
        label: item.addressName,
        isLeaf: false,
        parentId: item.addressCode,
      }));
      setOptions(arr);
      console.log(arr);
    }
  }

  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoding(true);
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (imageUrl) => {
        setLoding(false);
        setImageUrl(imageUrl);
      });
    }
  };

  const handleChange1 = (info) => {
    if (info.file.status === 'uploading') {
      setLoding1(true);
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (imageUrl) => {
        setLoding1(false);
        setImageUrl1(imageUrl);
      });
    }
  };

  function nextClick() {
    // form.validateFields().then(() => {
    setIsShow(false);
    son.current.nextChoose();
    son1.current.nextChoose();
    // });
  }
  const normFile = (e) => {
    //如果是typescript, 那么参数写成 e: any

    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  const normFile1 = (e) => {
    // if (e.fileList[0]?.response?.code == 200) {
    //   // setImageData1(e.fileList[0]?.response?.data);
    // }
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const loadData = (selectedOptions) => {
    // console.log(selectedOptions);
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    setTimeout(async () => {
      targetOption.loading = false;
      const res = await getAddressFn(2, targetOption.parentId);

      if (res.data.code == 200) {
        targetOption.children = res.data.data.map((item) => ({
          label: item.addressName,
          value: item.addressCode,
        }));
        setOptions([...options]);
      }
    }, 200);
  };
  const editFnLoadData = (arr) => {
    let parentId = arr[0].parentId;
    getAddressFn(2, parentId).then((res) => {
      let newOpions = JSON.parse(JSON.stringify(options));
      options.forEach((f, index) => {
        if (f.parentId == parentId) {
          newOpions[index].children = [];
          newOpions[index].children.push({
            label: arr[1].label,
            value: arr[1].parentId,
          });
          setOptions(newOpions);
        }
      });
    });
  };

  // const loadData1 = async (selectedOptions) => {
  //   console.log(selectedOptions);
  //   const targetOption = selectedOptions[selectedOptions.length - 1];
  //   const res = await getAddressFn(2, targetOption.parentId);

  //   if (res.data.code == 200) {
  //     targetOption.children = res.data.data.map((item) => ({
  //       label: item.addressName,
  //       value: item.addressCode,
  //     }));
  //     console.log('res', [...options]);
  //     setOptions([...options]);
  //   }
  // };

  async function getAddressFn(addressLevel, parentId) {
    return await formAddressApi({ addressLevel, parentId });
  }
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  const [active, setActive] = useState([
    { active: '报名', id: 1, isChoose: false },
    { active: '投票', id: 2, isChoose: false },
    { active: '门票', id: 3, isChoose: false },
    { active: '签到', id: 4, isChoose: false },
    { active: '抽奖', id: 5, isChoose: false },
  ]);
  const [activityType, setActivityType] = useState({});
  const [umpll, setUmpll] = useState({});

  const [apply, setApply] = useState(false);
  const [vote, setVote] = useState(false);

  function oneClick(e) {
    let arr3 = active.map((item) => {
      if (item.id == e) {
        item.isChoose = true;
      }
      return item;
    });

    setActive(arr3);
    if (e == 1) {
      setApply(true);
    }
    if (e == 2) {
      setVote(true);
    }
  }

  function twoClick(e) {
    let arr4 = active.map((item) => {
      if (item.id == e) {
        item.isChoose = false;
      }
      return item;
    });
    setActive(arr4);
    if (e == 1) {
      setApply(false);
    }
    if (e == 2) {
      setVote(false);
    }
  }
  //////////////////////////////////
  function draftClick() {
    console.log('6565565');
    let c = form.getFieldValue();
    console.log(c);
  }

  function lastClick() {
    setIsShow(true);
  }

  async function sonClick() {
    let p = active.findIndex((item) => {
      return item.isChoose == true;
    });
    if (p == -1) {
      alert('至少选一个活动');
    } else {
      const son1form = await son1.current.sonsClick();
      const sonform = await son.current.sonsClick();
      console.log('son1form', son1form);
      console.log('sonform', sonform);

      if (son1form && sonform) {
        let c = form.getFieldValue();
        let scheduleName = c.scheduleName?.map((item) => ({
          scheduleDate: moment(item.scheduleData).format('YYYY-MM-DD HH:mm'),
          scheduleName: item.scheduleName,
        }));

        let startDate = moment(c?.activityTime[0]).format('YYYY-MM-DD HH:mm');
        let endDate = moment(c?.activityTime[1]).format('YYYY-MM-DD HH:mm');

        const {
          activityName, //
          activityContent,
          activitySite,
          activityOrganizers,
          activityArea,
        } = c;
        if (props.history.location.state) {
          formSaveDrafts({
            activityBasicId: props.history.location.state.activityBasicId,
            activityName: activityName, //
            activityContent,
            activitySite,
            activityOrganizers,
            startDate, //
            endDate, //
            pictureKey: c.activityImg_3[0].name, //
            pictureUrl: c.activityImg_3[0].url,
            thumbnailPictureKey: c.activityImg_2[0].name, //
            thumbnailPictureUrl: c.activityImg_2[0].url, //
            provinceCode: activityArea[0], //
            cityCode: activityArea[1], //
            isSignUp: 1, //
            isRobTickets: 0, //
            isSignIn: 0, //
            isVote: 0, //
            isLuckyDraw: 0, //
            scheduleVOS: scheduleName,
            activityVOS: [sonform, son1form], //
          });
        } else {
          formSaveDrafts({
            activityName: activityName, //
            activityContent,
            activitySite,
            activityOrganizers,
            startDate, //
            endDate, //
            pictureKey: c.activityImg_3[0].response.data.imgKey, //
            pictureUrl: c.activityImg_3[0].response.data.imgUrl,
            thumbnailPictureKey: c.activityImg_2[0].response.data.imgKey, //
            thumbnailPictureUrl: c.activityImg_2[0].response.data.imgUrl, //
            provinceCode: activityArea[0], //
            cityCode: activityArea[1], //
            isSignUp: 1, //
            isRobTickets: 0, //
            isSignIn: 0, //
            isVote: 0, //
            isLuckyDraw: 0, //
            scheduleVOS: scheduleName,
            activityVOS: [sonform, son1form], //
          });
        }
      }
    }
  }

  return (
    <div>
      <div style={{ display: 'flex', marginTop: '10px' }}>
        <div>创建活动/</div>
        <div>创建活动</div>
      </div>

      <div className="addCreateActivity-title">
        <div style={{ paddingTop: '20px', marginTop: '10px' }}>
          <div className="title-item">创建活动</div>
          <div className="addCreateActivity-content">
            <div className="dot1"></div>
            <div className="wire1"></div>
            <div className={isShow ? 'wire2' : 'wire1'}></div>
            <div className={isShow ? 'dot2' : 'dot1'}></div>
          </div>
          <div className="msg-item">基本信息</div>
        </div>
      </div>

      {/* ============================================================================================================================================= */}
      <div className={isShow ? 'next-choose' : ''}>
        <div className="addCreateActivity-title">
          <div
            style={{
              marginBottom: '10px',
              marginLeft: '30px',
              paddingTop: '30px',
            }}
          >
            选择你想要创建的活动（可多选）
          </div>
          <div
            style={{ display: 'flex', marginLeft: '30px', marginTop: '30px' }}
          >
            {active.map((item) => {
              return (
                <div className="choose-list" key={item.id}>
                  <div
                    className={item.isChoose ? 'next-btn1' : 'next-btn'}
                    onClick={() => {
                      oneClick(item.id);
                    }}
                  >
                    {item.active}
                  </div>
                  <CloseCircleOutlined
                    className={item.isChoose ? 'icon-x' : 'icon-x1'}
                    onClick={() => {
                      twoClick(item.id);
                    }}
                  />
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* ============================================================================================================================================= */}

      <div
        className="site-layout-background"
        style={{ padding: 24, minHeight: '100vh' }}
      >
        <div className={isShow ? '' : 'next-choose'}>
          <div className="title-up">
            <div className="icon-title"></div>
            <div className="title-text">请填写活动的基本信息</div>
          </div>

          <Form name="basic" autoComplete="off" form={form}>
            <div className="head-all">
              <div className="head-form">
                <Form.Item
                  label="活动名称"
                  name="activityName"
                  rules={[
                    {
                      required: true,
                      message: '请输入活动名称',
                    },
                  ]}
                >
                  <Input style={{ width: '400px' }} />
                </Form.Item>
                <Form.Item
                  label="地区选择"
                  name="activityArea"
                  rules={[{ required: true, message: '请选择地区' }]}
                >
                  <Cascader
                    style={{ width: '400px' }}
                    options={options}
                    loadData={loadData}
                    changeOnSelect
                    placeholder="请选择活动所属地区"
                  />
                </Form.Item>
              </div>
              <div className="head-form">
                <Form.Item
                  name="activityTime"
                  label="活动时间"
                  rules={[
                    {
                      required: true,
                      message: '请输入活动时间',
                    },
                  ]}
                >
                  <RangePicker
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                    style={{ width: '400px' }}
                  />
                </Form.Item>
                <Form.Item label="活动地点" name="activitySite">
                  <Input
                    style={{ width: '400px' }}
                    placeholder="请输入活动地点"
                  />
                </Form.Item>
              </div>
              <div className="head-form">
                <Form.Item label="活动主办方" name="activityOrganizers">
                  <Input
                    style={{ width: '400px' }}
                    placeholder="请输入活动主办方"
                  />
                </Form.Item>
                <Form.Item
                  name="activityContent"
                  label="活动内容"
                  rules={[
                    {
                      required: true,
                      message: '请输入活动内容',
                    },
                  ]}
                >
                  <Input.TextArea
                    showCount
                    maxLength={100}
                    style={{ width: '400px' }}
                  />
                </Form.Item>
              </div>
              <div className="head-form1">
                <div style={{ marginRight: '470px' }}>
                  {/* <Form.Item label="活动图"> */}
                  <Form.Item
                    label="活动图"
                    name="activityImg_3"
                    // 以下两条是必须的
                    valuePropName="fileList"
                    // 如果没有下面这一句会报错
                    getValueFromEvent={normFile}
                    rules={[{ required: true, message: '请上传活动图' }]}
                  >
                    <Upload
                      name="multipartFile"
                      listType="picture-card"
                      className="avatar-uploader"
                      showUploadList={false}
                      action="/campus/campusweb/upload/pictureUpload"
                      onChange={handleChange1}
                    >
                      {imageUrl1 ? (
                        <img
                          src={imageUrl1}
                          alt="avatar"
                          style={{ width: '100%' }}
                        />
                      ) : (
                        <div>
                          {loading1 ? <LoadingOutlined /> : <PlusOutlined />}
                          <div style={{ marginTop: 8 }}>Upload</div>
                        </div>
                      )}
                    </Upload>
                  </Form.Item>
                  <span>推荐尺寸</span>
                  {/* </Form.Item> */}
                </div>

                <Form.Item label="略缩图">
                  <Form.Item
                    name="activityImg_2"
                    // 以下两条是必须的
                    valuePropName="fileList"
                    // 如果没有下面这一句会报错
                    getValueFromEvent={normFile1}
                    rules={[{ required: true, message: '请上传活动图' }]}
                  >
                    <Upload
                      name="multipartFile"
                      listType="picture-card"
                      className="avatar-uploader"
                      showUploadList={false}
                      action="/campus/campusweb/upload/pictureUpload"
                      onChange={handleChange}
                    >
                      {imageUrl ? (
                        <img
                          src={imageUrl}
                          alt="avatar"
                          style={{ width: '100%' }}
                        />
                      ) : (
                        <div>
                          {loading ? <LoadingOutlined /> : <PlusOutlined />}
                          <div style={{ marginTop: 8 }}>Upload</div>
                        </div>
                      )}
                    </Upload>
                  </Form.Item>
                  <div>推荐尺寸</div>
                </Form.Item>
              </div>
            </div>

            <div className="title-up">
              <div className="icon-title"></div>
              <div className="title-text">
                请编辑活动日程规划 <span>(可添加多项)</span>
              </div>
            </div>
            <Form.List name="scheduleName">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space
                      key={key}
                      style={{ display: 'flex', marginBottom: 8 }}
                      align="baseline"
                    >
                      <Form.Item name={[name, 'scheduleName']} {...restField}>
                        <Input placeholder="请输入日程名称" />
                      </Form.Item>
                      <Form.Item name={[name, 'scheduleDate']} {...restField}>
                        <DatePicker showTime placeholder="请选择日程时间" />
                      </Form.Item>

                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      block
                      icon={<PlusOutlined />}
                    >
                      Add field
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Form>
          <div style={{ display: 'flex' }}>
            <div className="btn-next" onClick={nextClick}>
              下一步
            </div>
            <div className="btn-next">预览</div>
            <div className="btn-next" onClick={draftClick}>
              保存草稿
            </div>
          </div>
        </div>
        {/* 第二页 =============================================================================================================================*/}
        <div className={apply && !isShow ? '' : 'apply-item'}>
          <ApplyActive ref={son} allData={allData}></ApplyActive>
        </div>
        <div className={vote && !isShow ? '' : 'vote-item'}>
          <VoteActive ref={son1} allData={allData}></VoteActive>
        </div>
        <div className={isShow ? 'next-choose' : ''}>
          <div style={{ display: 'flex', marginTop: '50px' }}>
            <div className="btn-next">发布</div>
            <div className="btn-next" onClick={lastClick}>
              上一步
            </div>
            <div className="btn-next">预览</div>
            <div className="btn-next" onClick={sonClick}>
              保存草稿
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
